import base64

import pickle
from django.shortcuts import render
from django.views import View
import json
from django import http
from django_redis import get_redis_connection

from apps.goods.models import SKU
from meiduo_mall.utils.response_code import RETCODE
# Create your views here.



###########购物车管理#################
class CartsView(View):

    def post(self,request):
        """添加购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get("sku_id")
        count = json_dict.get("count")
        selected = json_dict.get("selected",True)

        # 判断参数是否齐全
        if not all([sku_id,count]):
            return http.HttpResponseForbidden("缺少必传参数")
        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden("商品不存在")
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden("参数count有误")
        # 判断selected是否是bool
        if not isinstance(selected,bool):
            return http.HttpResponseForbidden("参数selected有误")

        # 判断用户是否登陆
        user = request.user
        if user.is_authenticated:
            # 如果用户已登陆,添加redis购物车
            # 连接redis
            redis_conn = get_redis_connection("carts")
            pl = redis_conn.pipeline()

            # 判断需要添加的商品在购物车中是否存在,如果存在累加,反之新建购物车记录
            pl.hincrby("carts_%s" % user.id, sku_id,count)
            # redis_cart = redis_conn.hget("cart_%s" % user.id)
            # origin_count = redis_cart[sku_id]
            # if count:
            #     count += origin_count
            # redis_conn.hset("cart_%s" %user.id,sku_id,count)

            # 添加商品勾选状态
            if selected:
                pl.sadd("selected_%s" % user.id,sku_id)
            # 执行管道
            pl.execute()

            # 响应结果
            return http.JsonResponse({"code":RETCODE.OK,"errmsg":"添加购物车成功"})
        else:
            # 如果用户未登陆,添加cookie购物车
            # 1. 从cookie中读取购物车字典
            cart_str = request.COOKIES.get("carts")
            if cart_str:
                # 先将cart_str编码为cart_str_bytes
                cart_str_bytes = cart_str.encode()
                # 再使用base64将cart_str_bytes解码为cart_dict_bytes
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 再使用pickle将cart_dict_bytes反序列化为cart_dic
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}

            # 2.添加购物车数据到购物车字典:添加逻辑同登录用户购物车的添加逻辑
            if sku_id in cart_dict:
                # 取出原有的商品数量
                origin_count = cart_dict[sku_id]['count']
                # 累加商品数量
                count += origin_count # count = origin_count + count
            cart_dict[sku_id] = {
                "count": count,
                "selected": selected
            }

            # 3.购物车字典转字符串并写入到cookie
            # 先使用pickle将cart_dict序列化为cart_dict_bytes
            cart_dict_bytes = pickle.dumps(cart_dict)
            # 再使用base64将cart_dict_bytes编码为cart_str_bytes
            cart_str_bytes = base64.b64encode(cart_dict_bytes)
            # 再将cart_str_bytes转成cart_str
            cookie_cart_str = cart_str_bytes.decode()

            # 创建响应对象
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})

            # 将cookie_cart_str写入到cookie
            response.set_cookie('carts', cookie_cart_str)
            return response


    def get(self,request):
        """展示购物车"""
        user = request.user
        if user.is_authenticated:
            # 用户已登录，查询redis购物车
            # 创建连接redis对象
            redis_conn = get_redis_connection("carts")
            # 读取hash中的商品和数量
            redis_cart = redis_conn.hgetall("carts_%s" % user.id)

            # 读取set中的勾选状态(被勾选商品的sku_id)
            redis_selected = redis_conn.smembers("selected_%s" %user.id)

            # 定义一个新的购物车字典
            cart_dict = {}
            # 便利redis_cart取出skuid和count
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    "count":int(count),
                    # 方式一也可以
                    # "selected":True if sku_id in redis_selected else False
                    "selected": sku_id in redis_selected
                }

        else:
            # 用户未登录，查询cookies购物车
            # 从cookie中读取购物车密文字符串
            cart_str = request.COOKIES.get("carts")
            # 将购物车密文字符串购物车转成字典
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        # 登陆用户或者未登录用户的购物车转成字典
        # 通过购物车字典中的sku_id查询出对象的sku
        sku_ids = cart_dict.keys()
        # 两个都可以
        # for sku_id in sku_ids:
        #     sku = SKU.objects.get(id=sku_id)
        skus = SKU.objects.filter(id__in=sku_ids)

        #　再将商品数据转为字典
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'default_image_url': sku.default_image.url,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': str(cart_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
                'amount': str(sku.price * cart_dict.get(sku.id).get('count'))
            })

        # 构造上下文
        context = {
            "cart_skus":cart_skus
        }

        return render(request, 'cart.html',context)


    def put(self,request):
        """修改购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get("sku_id")
        count = json_dict.get("count")
        selected = json_dict.get("selected", True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden("缺少必传参数")
        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden("商品不存在")
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden("参数count有误")
        # 判断selected是否是bool
        if not isinstance(selected, bool):
            return http.HttpResponseForbidden("参数selected有误")

        # 判断用户是否登陆
        user = request.user
        if user.is_authenticated:
            # 用户登陆，修改redis购物车(前端发送的count和selected时修改之后的结果,覆盖即可)
            redis_conn = get_redis_connection("carts")
            pl = redis_conn.pipeline()
            pl.hset("carts_%s"% user.id,sku_id,count)
            # 判断用户传入的状态是否是勾选的
            if selected:
                # 如果用户传入的勾选状态为已勾选,将sku_id添加到set
                pl.sadd("selected_%s" % user.id,sku_id)
            else:
                # 如果未勾选,将sku_id从set中移除
                pl.srem("selected_%s" % user.id,sku_id)
            # 执行
            pl.execute()

            # 构造要响应的新的购物车数据
            cart_sku = {
                'id': sku_id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url,
                'count': count,
                'selected': selected,
                'amount': sku.price * count
            }

            # 响应结果
            return http.JsonResponse({"code":RETCODE.OK,"errmsg":"修改购物车成功",
                                      "cart_sku":cart_sku})
        else:
            # 用户未登录,修改cookie购物车
            # 从cookie读取购物车字典
            cart_str = request.COOKIES.get("carts")
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

            # 修改购物车字典:覆盖写入
            cart_dict[sku_id] = {
                "count":count,
                "selected":selected
            }

            # 将购物车字典转字符串写入到cookie
            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 构造要响应的新的购物车数据
            cart_sku = {
                'id': sku_id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url,
                'count': count,
                'selected': selected,
                'amount': sku.price * count
            }

            # 将购物车数据写入cookie
            response = http.JsonResponse({"code":RETCODE.OK,"errmsg":"修改购物车成功",
                                      "cart_sku":cart_sku})

            response.set_cookie("carts",cookie_cart_str)
            return response


    def delete(self,request):
        """删除购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，删除redis购物车
            # 连接redis
            redis_conn = get_redis_connection("carts")
            pl = redis_conn.pipeline()

            # 删除hash中的购物车数据
            pl.hdel("carts_%s" % user.id,sku_id)
            pl.srem("selected_%s" % user.id,sku_id)
            # 执行
            pl.execute()

            # 响应结果
            return http.JsonResponse({"code":RETCODE.OK,"errmmsg":"删除购物车成功"})

        else:
            # 用户未登录，删除cookie购物车
            # 从cookie中读取购物车字典
            cart_str = request.COOKIES.get("carts")
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
            # 删除购物车字典中的key
            if sku_id in cart_dict:
                del cart_dict[sku_id]

            # 将新的购物车字典转成字符串拼写到cookie
            cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()

            response = http.JsonResponse({"code":RETCODE.OK,"errmsg":"删除购物车成功"})
            response.set_cookie("carts",cookie_cart_str)
            return response






